(function () {
    var core = ecui,
        util = core.util,
        dom = ecui.dom,
        ustart = null,
        uend = null,
        start = null,
        end = null,
        udays = [],
        count = 0;

    /**
     * 选中某个日期单元格。
     * @private
     *
     * @param {ecui.ui.MonthView} view 日历视图对象
     * @param {ecui.ui.MonthView.Cell} cell 日期单元格对象
     */
    function setSelected(view, cell) {
        if (view._cSelected !== cell) {
            if (cell) {
                cell.alterStatus('+selected');
                view._cSelected = cell;
            }
        }
    }
    /**
     * 选中某个日期单元格。
     * @private
     *
     * @param {ecui.ui.MonthView} view 日历视图对象
     * @param {ecui.ui.MonthView.Cell} cell 日期单元格对象
     */
    function setSelectedRange() {
        if (!udays.length) {
            ecui.query(function (item) {
                return item instanceof ecui.ui.MonthView;
            }).forEach(function (item) {
                udays = udays.concat(item.getDays());
            });
        }
        if (!ustart || !uend) {
            return;
        }
        var flag;
        for (var i = 0, item; item = udays[i++]; ) {
            if (item === ustart) {
                console.log('setSelectedRange');
                flag = true;
            }
            if (flag) {
                item.alterStatus('+range');
            } else if (flag === false) {
                return;
            }
            if (item === uend) {
                flag = false;
                return;
            }
        }
    }
    window.setSelectedRange = setSelectedRange;
    function clearSelectedRange() {
        if (!udays.length) {
            ecui.query(function (item) {
                return item instanceof ecui.ui.MonthView;
            }).forEach(function (item) {
                udays = udays.concat(item.getDays());
            });
        }
        udays.forEach(function (item) {
            item.alterStatus('-range');
        });
    }
    ecui.util.extend(NS.ui, {
        BookIndex: ecui.inherits(
            ecui.ui.MPanel,
            {
                format: '{0}年',
                onclick: function (event) {
                    dom.next(this.getMain()).getControl().moveTo(util.stringFormat(this.format, event.target.innerHTML));
                }
            }
        ),
        DayItem: ecui.inherits(
            ecui.ui.Control,
            function (el, options) {
                ecui.ui.Control.call(this, el, options);
                this.start = options.start;
                this.end = options.end;
                this._eText = options.text;

                this.mtype = options.mtype;
                this.year = +options.year;
                this.index = +options.index;

                var end = options.end.split('-');
                if (end.length === 2) {
                    this.end = new Date(end[0], end[1], 0).pattern('yyyy-MM-dd');
                }
            },
            {
                onclick: function (event) {
                    var route = ecui.esr.getRoute('/home/index'),
                        form = document.forms.indexStatisticsForm,
                        textEl = dom.children(form)[1];

                    dom.removeClass(textEl, 'small');
                    textEl.innerHTML = this._eText;
                    document.forms.indexStatisticsForm.elements.startDate.value = this.start;
                    document.forms.indexStatisticsForm.elements.endDate.value = this.end;
                    route.statistics = true;
                    route.mtype = this.mtype;
                    route.year = this.year;
                    route.index = this.index;

                    history.go(-1);
                }
            }
        ),
        Tab: ecui.inherits(
            ecui.ui.Tab,
            {
                FIRST: true,
                ontitleclick: function (event) {
                    if (this.FIRST && event.index === 2) {
                        this.FIRST = false;
                        var monthBook = ecui.get('month-book');
                        util.timer(function () {
                            var top = -monthBook.getBody().clientHeight + monthBook.getHeight();
                            monthBook.setScrollRange({ top: top });
                            monthBook.setPosition(0, top);
                        }, 0);
                    }
                }
            }
        ),
        MonthView: ecui.inherits(
            ecui.ui.MonthView,
            {
                onready: function () {
                    util.timer(function () {
                        this._cSelected.alterStatus('-selected');
                        this._cSelected = null;
                    }, 0, this);
                },
                $dateclick: function (event) {
                    this._oDate = event.date;
                    var preview = dom.children(ecui.$('dayPreview'));
                    setSelected(this, event.item);
                    if (++count % 2) {
                        if (ustart) {
                            ustart.alterStatus('-selected');
                        }
                        if (uend) {
                            uend.alterStatus('-selected');
                        }
                        start = event.date;
                        ustart = event.item;
                        end = null;
                        uend = null;
                        preview[0].innerHTML = '开始时间：' + event.date.pattern('yyyy年MM月dd日');
                        preview[1].innerHTML = '结束时间：';
                        clearSelectedRange();
                        preview[2].getControl().disable();
                    } else {
                        if (event.date < start) {
                            end = start;
                            uend = ustart;
                            start = event.date;
                            ustart = event.item;
                            preview[0].innerHTML = '开始时间：' + start.pattern('yyyy年MM月dd日');
                            preview[1].innerHTML = '结束时间：' + end.pattern('yyyy年MM月dd日');
                        } else {
                            end = event.date;
                            uend = event.item;
                            preview[1].innerHTML = '结束时间：' + event.date.pattern('yyyy年MM月dd日');
                        }
                        setSelectedRange();
                        preview[2].getControl().enable();
                    }
                }
            }
        ),
        SureBtn: ecui.inherits(
            ecui.ui.Control,
            {
                onclick: function () {
                    var text = '',
                        form = document.forms.indexStatisticsForm,
                        elements = form.elements,
                        textEl = dom.children(form)[1];

                    if (start.getFullYear() === end.getFullYear()) {
                        dom.removeClass(textEl, 'small');
                        text = start.getFullYear() + '年' + start.pattern('MM月dd日') + '-' + end.pattern('MM月dd日');
                    } else {
                        if (!dom.hasClass(textEl, 'small')) {
                            dom.addClass(textEl, 'small');
                        }
                        text = start.pattern('yyyy年MM月dd日') + '-' + end.pattern('yyyy年MM月dd日');
                    }
                    textEl.innerHTML = text;
                    document.forms.indexStatisticsForm.elements.startDate.value = start.pattern('yyyy-MM-dd');
                    document.forms.indexStatisticsForm.elements.endDate.value = end.pattern('yyyy-MM-dd');
                    ecui.esr.getRoute('/home/index').statistics = true;
                    delete ecui.esr.getRoute('/home/index').mtype;
                    history.go(-1);
                }
            }
        )
    });
    function getWeeks(year) {
        var weeks = [],
            i = 0,
            now = new Date(),
            start = new Date(year, 0, 1),
            end = new Date(year + 1, 0, 1);

        if (start.getDay() !== 1) {
            weeks.push({
                index: ++i,
                start: start,
                end: new Date(year, 0, 7 - start.getDay())
            });
        }
        start = new Date(year, 0, 8 - start.getDay());
        end = end < now ? end : now;
        for (; start < end; ) {
            var endDay = new Date(year, start.getMonth(), start.getDate() + 6);
            if (endDay >= end) {
                weeks.push({
                    index: ++i,
                    start: start,
                    end: new Date(year, start.getMonth(), start.getDate() + end.getDay() - 1)
                });
            } else {
                weeks.push({
                    index: ++i,
                    start: start,
                    end: new Date(year, start.getMonth(), start.getDate() + 6)
                });
            }
            start = new Date(year, start.getMonth(), start.getDate() + 7);
        }
        return weeks.reverse();
    }
    function getMonth(year) {

        var month = [],
            now = new Date(),
            start = 1,
            end = 12;

        end = year === now.getFullYear() ? now.getMonth() + 1 : 12;
        for (; start <= end; start++) {
            month.push({
                month: start,
                start: new Date(year, start - 1, 1),
                end: new Date(year, start, 0)
            });
        }
        return month;
    }
    ecui.esr.addRoute('period', {
        model: [
            // 'detail@GET /erp-management/venue/order/${orderSn}'
        ],
        weight: 2,
        main: 'home_period',
        view: 'period',
        frame: true,
        onbeforerequest: function (context) {

        },
        onbeforerender: function (context) {
            var now = new Date(),
                year = now.getFullYear();
            context.period = [];
            context.custom = [];
            for (var i = 0; i < 5; i++) {
                context.period.push({ year: year - i, weeks: getWeeks(year - i)});
                context.custom.push({ year: year - i, month: getMonth(year - i)});
            }
            context.month = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
            context.now = { year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate() };
            context.custom = context.custom.reverse();
            // console.log(context.period, context.custom);
        },
        onafterrender: function () {
        }
    });
}());